import { NotifyService } from '@abp/notify/notify.service';
import {
  Component,
  Injector,
  ViewChild,
  ViewEncapsulation,
  ElementRef,
  OnInit
} from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
  ComboboxItemDto, TechRuleServiceProxy, TechRuleListDto, TechFileInfoServiceProxy, TechRuleInfoDto, TechRuleInfoListDto,
} from '@shared/service-proxies/service-proxies';
import { FileDownloadService } from '@shared/utils/file-download.service';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { CreateOrEditTechRuleModalComponent } from './create-or-edit-techrule-modal.component';
import { ActionTechRuleModalComponent } from './action-techrule-modal.component';
import { EditOutOrBackTechRuleModalComponent } from './edit-out-or-back-techrule-modal.component';
import * as moment from 'moment';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';

@Component({
  templateUrl: './techrule.component.html',
  encapsulation: ViewEncapsulation.None,
  styleUrls: ['./techrule.component.less'],
  animations: [appModuleAnimation()]
})
export class TechRulesComponent extends AppComponentBase implements OnInit {
  @ViewChild('createOrEditTechRuleModal')
  createOrEditTechRuleModal: CreateOrEditTechRuleModalComponent;
  @ViewChild('actionTechRuleModal')
  actionTechRuleModal: ActionTechRuleModalComponent;
  @ViewChild('editOutOrBackTechRuleModal')
  editOutOrBackTechRuleModal: EditOutOrBackTechRuleModalComponent;
  @ViewChild('dataTable') dataTable: Table;
  @ViewChild('paginator') paginator: Paginator;
  @ViewChild('dataTable1') dataTable1: Table;
  @ViewChild('paginator1') paginator1: Paginator;
  @ViewChild('dataTable2') dataTable2: Table;
  @ViewChild('stageTypeCombobox') stageTypeCombobox: ElementRef;
  @ViewChild('securityTypeCombobox') securityTypeCombobox: ElementRef;
  primengTableHelper1 = new PrimengTableHelper();
  primengTableHelper2 = new PrimengTableHelper();
  advancedFiltersAreShown = false;
  filterText = '';

  stages: Array<ComboboxItemDto> = new Array<ComboboxItemDto>();
  securitys: Array<ComboboxItemDto> = new Array<ComboboxItemDto>();

  stage = -1;
  security = -1;
  filetype = -1;
  startFilterDate: Date;
  endFilterDate: Date;

  type = 1;

  constructor(
    injector: Injector,
    private _techruleServiceProxy: TechRuleServiceProxy,
    private _techfileServiceProxy: TechFileInfoServiceProxy,
    private _fileDownloadService: FileDownloadService
  ) {
    super(injector);
  }

  ngOnInit(): void {
    this.getstage();
    this.getsecurity();
  }

  selectType(type: number) {
    this.type = type;
  }

  getstage() {
    this._techfileServiceProxy.getComboboxItemForStageType().subscribe(result => {
      this.stages = result;
      setTimeout(() => {
        $(this.stageTypeCombobox.nativeElement).selectpicker('refresh');
      });
    });
  }

  getsecurity() {
    this._techfileServiceProxy.getComboboxItemForSecurityType().subscribe(result => {
      this.securitys = result;
      setTimeout(() => {
        $(this.securityTypeCombobox.nativeElement).selectpicker('refresh');
      });
    });
  }

  getTechRules(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.paginator.changePage(0);
      return;
    }

    this.primengTableHelper.showLoadingIndicator();

    this._techruleServiceProxy
      .getTechRules(
        this.filterText,
        this.stage === -1 ? undefined : this.stage,
        this.security === -1 ? undefined : this.security,
        true,
        false,
        this.startFilterDate ? moment(this.startFilterDate) : null,
        this.endFilterDate ? moment(this.endFilterDate) : null,
        this.primengTableHelper.getSorting(this.dataTable),
        this.primengTableHelper.getMaxResultCount(this.paginator, event),
        this.primengTableHelper.getSkipCount(this.paginator, event)
      )
      .subscribe(result => {
        this.primengTableHelper.totalRecordsCount = result.totalCount;
        this.primengTableHelper.records = result.items;
        this.primengTableHelper.hideLoadingIndicator();
      });
  }

  getTechRules1(event?: LazyLoadEvent) {
    if (this.primengTableHelper1.shouldResetPaging(event)) {
      this.paginator1.changePage(0);
      return;
    }

    this.primengTableHelper1.showLoadingIndicator();

    this._techruleServiceProxy
      .getTechRules(
        this.filterText,
        this.stage === -1 ? undefined : this.stage,
        this.security === -1 ? undefined : this.security,
        false,
        false,
        this.startFilterDate ? moment(this.startFilterDate) : null,
        this.endFilterDate ? moment(this.endFilterDate) : null,
        this.primengTableHelper1.getSorting(this.dataTable1),
        this.primengTableHelper1.getMaxResultCount(this.paginator1, event),
        this.primengTableHelper1.getSkipCount(this.paginator1, event)
      )
      .subscribe(result => {
        this.primengTableHelper1.totalRecordsCount = result.totalCount;
        this.primengTableHelper1.records = result.items;
        this.primengTableHelper1.hideLoadingIndicator();
      });
  }

  getTechRules2(event?: LazyLoadEvent) {
    this.primengTableHelper2.showLoadingIndicator();

    this._techruleServiceProxy
      .getTechRules(
        this.filterText,
        this.stage === -1 ? undefined : this.stage,
        this.security === -1 ? undefined : this.security,
        true,
        true,
        this.startFilterDate ? moment(this.startFilterDate) : null,
        this.endFilterDate ? moment(this.endFilterDate) : null,
        this.primengTableHelper2.getSorting(this.dataTable2),
        999,
        0
      )
      .subscribe(result => {
        this.primengTableHelper2.totalRecordsCount = result.totalCount;
        this.primengTableHelper2.records = result.items;
        this.primengTableHelper2.hideLoadingIndicator();
      });
  }

  reloadPage(): void {
    this.paginator.changePage(this.paginator.getPage());
    this.paginator1.changePage(this.paginator1.getPage());
    this.getTechRules2();
  }

  exportToExcel(event?: LazyLoadEvent): void {
    this._techruleServiceProxy
      .getTechRulesToExcel(this.filterText,
        this.stage === -1 ? undefined : this.stage,
        this.security === -1 ? undefined : this.security,
        this.type === 1 ? true : false,
        this.type === 3 ? true : false,
        this.startFilterDate ? moment(this.startFilterDate) : null,
        this.endFilterDate ? moment(this.endFilterDate) : null,
        this.primengTableHelper.getSorting(this.dataTable),
        this.primengTableHelper.getMaxResultCount(this.paginator, event),
        this.primengTableHelper.getSkipCount(this.paginator, event))
      .subscribe(result => {
        this._fileDownloadService.downloadTempFile(result);
      });
  }

  onUpload(event) {
    let list = event as Array<any>;

    let techrules = list.map(el => {
      let file = new TechRuleInfoListDto();
      file.fileCode = el.文件编号;
      file.techRuleType = el.工艺规程类型;
      file.isPaper = el.纸质形式;
      file.useUnit = el.使用单位;
      file.useTime = el.使用时间;
      file.fromGist = el.依据文件;
      file.fileName = el.文件信息名称;
      file.modelName = el.型号;
      file.drawingCode = el.图号;
      file.drawingName = el.图号名称;
      file.stage = el.阶段;
      file.security = el.密级;
      file.remark = el.备注;
      return {
        techRuleInfo: file
      };
    }) as Array<TechRuleListDto>;

    this.message.confirm(
      '确认导入这' + list.length + '条数据吗？',
      this.l('AreYouSure'),
      isConfirmed => {
        if (isConfirmed) {
          this.primengTableHelper.showLoadingIndicator();
          this._techruleServiceProxy
            .importGeneralTools(techrules)
            .subscribe(result => {
              this.reloadPage();
              this.notify.success('导入数据成功');
            });
        }
      }
    );
  }

  deleteTechRule(techrule: TechRuleListDto): void {
    this.message.confirm(
      '确认删除该工规(' + techrule.techRuleInfo.fileCode + ')',
      this.l('AreYouSure'),
      isConfirmed => {
        if (isConfirmed) {
          this._techruleServiceProxy.deleteTechRule(techrule.id).subscribe(() => {
            this.reloadPage();
            this.notify.success(this.l('SuccessfullyDeleted'));
          });
        }
      }
    );
  }

  showAction(type: number) {
    this.actionTechRuleModal.show(type);
  }

  goCar(techrule: TechRuleListDto, type: number) {
    this._techruleServiceProxy.goCar(techrule.id, type).subscribe(() => {
      this.reloadPage();
      this.notify.success('加入成功');
    });
  }

  cancelCar(techrule: TechRuleListDto) {
    this._techruleServiceProxy.cancelCar(techrule.id).subscribe(() => {
      this.reloadPage();
      this.notify.success('取消成功');
    });
  }

  search() {
    this.paginator.changePage(this.paginator.getPage());
    this.paginator1.changePage(this.paginator1.getPage());
  }
}
